//
//  BXPUserHomeViewController.swift
//  XerxesPP
//
//  Created by 向攀 on 2017/8/16.
//  Copyright © 2017年 Boos－XP. All rights reserved.
//

import UIKit

class BXPUserHomeViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate, BXPUserHomeHeaderViewDelegate, ScrollableTitleBarDelegate, BXPUserHomeBaseTableViewControllerDelegate, UINavigationControllerDelegate {

    let headerViewHeight: CGFloat = 400
    
    
    var userID = ""
    var pageViewController: UIPageViewController!
    
    var pageChildViewControllers:[UIViewController] = []
    
    var isPageScrollable = true
    
    var currenPageChildController: BXPUserHomeBaseTableViewController!
    var edgeGesture: UIScreenEdgePanGestureRecognizer?

    
    init(NIMUserID: String) {
        super.init(nibName: nil, bundle: nil)
        
        userID = NIMUserID
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.navigationBar.alpha = 0.01

//        UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.navigationBar.alpha = 1.0
    }

//    override func viewDidAppear(_ animated: Bool) {
//        super.viewDidAppear(animated)
//
////        navigationController?.setNavigationBarHidden(false, animated: true)
//        navigationController?.navigationBar.alpha = 0.01
//    }
    
//    override func viewWillDisappear(_ animated: Bool) {
//        super.viewWillDisappear(animated)
//
////        navigationController?.setNavigationBarHidden(false, animated: true)
//        navigationController?.navigationBar.alpha = 1.0
////        UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
//    }
    
//    override func viewDidDisappear(_ animated: Bool) {
//        super.viewDidDisappear(animated)
//        navigationController?.navigationBar.alpha = 1.0
//    }
    
    var isStatusBarStyleDefault = false
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return isStatusBarStyleDefault ? UIStatusBarStyle.default : UIStatusBarStyle.lightContent
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        automaticallyAdjustsScrollViewInsets = false

        setupPageChildViewControllers()
        setupPageViewController()

//        view.addSubview(titleBar)
        headerView.addSubview(titleBar)
        setupUI()

//        for subView in pageViewController.view.subviews {
//            if subView.isKind(of: UIScrollView.self) {
//                let scrollV = subView as! UIScrollView
////                scrollV.delegate = self
//                scrollV.alwaysBounceHorizontal = false
////                scrollV.bounces = false
//            }
//        }

//        let edgeGes = UIScreenEdgePanGestureRecognizer(target: navigationController?.interactivePopGestureRecognizer?.delegate, action: #selector(handleNavigationTransition(_:)))
//        edgeGes.edges = .left
//        edgeGes.delegate = self
//        view.addGestureRecognizer(edgeGes)

        
        NotificationCenter.default.addObserver(self, selector: #selector(backFromBackground), name: UIApplication.didBecomeActiveNotification, object: nil)
        
        navigationController?.delegate = self
    }
    
    
    
    func setupPageChildViewControllers() -> Void {
        
        let profileVC = BXPUserHomeBaseTableViewController()
        profileVC.setupHeaderHeight(headerViewHeight, offsetYObserver: self)
        pageChildViewControllers.append(profileVC)
        
        
        let contentListViewViewController = BXPUserProfileViewController()
        contentListViewViewController.setupHeaderHeight(headerViewHeight, offsetYObserver: self)
        pageChildViewControllers.append(contentListViewViewController)
        
        
        let photoVC = BXPUserHomeBaseTableViewController()
        photoVC.setupHeaderHeight(headerViewHeight, offsetYObserver: self)
        pageChildViewControllers.append(photoVC)
        
    }
    
    func setupPageViewController() -> Void {
        
        pageViewController = BXPPageViewController(transitionStyle: UIPageViewController.TransitionStyle.scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal, options: nil)
        pageViewController.setViewControllers([pageChildViewControllers[0]], direction: UIPageViewController.NavigationDirection.reverse, animated: false, completion: nil)
        addChild(pageViewController)
        view.addSubview(pageViewController.view)
        pageViewController.delegate = self
        pageViewController.dataSource = self
        pageViewController.view.snp.makeConstraints { (make) in
            make.top.left.bottom.right.equalToSuperview()
        }
        
        for view in pageViewController.view.subviews {
            if view.isKind(of: UIScrollView.self) {
                let scrollV = view as! UIScrollView
                scrollV.delegate = self
            }
        }

        
        //设置默认子控制器
        currenPageChildController = pageChildViewControllers[0] as! BXPUserHomeBaseTableViewController
        currenPageChildController.setupHeaderView(headerView)
    }

    private func setupUI() -> Void {
        view.backgroundColor = UIColor.white
        
        setupNavLeftButton()
    }

    private func setupNavLeftButton() -> Void {

        view.addSubview(leftButton)
    }

    @objc private func navLeftBackButtonClicked() -> Void {
        navigationController?.popViewController(animated: true)
        return
            
        UIView.animate(withDuration: 0.5, animations: {
            self.view.transform = CGAffineTransform(translationX: 375, y: 0)
        }) { (fil) in
            self.navigationController?.popViewController(animated: false)
        }
    }
    
    private lazy var headerView: BXPUserHomeHeaderView = {
        let tempView = BXPUserHomeHeaderView(frame: CGRect.zero, delegate: self)
        
        return tempView
    }()
    
    private lazy var titleBar: ScrollableTitleBar = {
        let tempView = ScrollableTitleBar(frame: CGRect(x: 0, y: self.headerViewHeight - 50, width: UIScreen.main.bounds.size.width, height: 50), titles: ["简介", "主页", "相册"], currentIndex: 0, titleFont: UIFont.systemFont(ofSize: 14), titleMinWidth: 20, titleMaxWidth: 0)
        tempView.setTitleAttribute(color: UIColor.gray, selectedColor: UIColor.red, bottomLineColor: UIColor.red, bottomLineHeight: 2)
        tempView.delegate = self
        return tempView
    }()
    
    private lazy var titleView: UIView = {
        let tempView = UIView(frame: CGRect(x: 0, y: self.headerViewHeight - 55, width: UIScreen.main.bounds.size.width, height: 55))
        tempView.backgroundColor = ColorBackground
        
        var titleBarFrame = tempView.bounds
        titleBarFrame.size.height -= 5
        let titleBar = ScrollableTitleBar(frame: titleBarFrame, titles: ["简介", "主页", "相册"], currentIndex: 0, titleFont: UIFont.systemFont(ofSize: 15), titleMinWidth: 20, titleMaxWidth: 0)
        titleBar.setTitleAttribute(color: UIColor.gray, selectedColor: UIColor.red, bottomLineColor: UIColor.red, bottomLineHeight: 2)
        titleBar.delegate = self
        tempView.addSubview(titleBar)
        
        self.view.addSubview(tempView)
        return tempView
    }()

    private lazy var leftButton: UIButton = {
        let button = UIButton(frame: CGRect(x: 5, y: 21, width: 40, height: 40))
        
        button.contentEdgeInsets = UIEdgeInsets(top: 7, left: 0, bottom: 6, right: 20)
        button.setImage(UIImage(named: "nav_back_white"), for: .normal)
        button.addTarget(self, action: #selector(navLeftBackButtonClicked), for: .touchUpInside)

        return button
    }()

    @objc private func handleNavigationTransition(_ gestureRecognizer: UIGestureRecognizer) -> Void {
        print("-----------xp----nav-ges")
    }

    
    //MARK: - observer
    @objc private func backFromBackground() -> Void {
        userHomeBaseTableViewController(controller: currenPageChildController, didScroll: currenPageChildController.getViewContentOffsetY())
    }
    
    
    //MARK: - ScrollableTitleBarDelegate
    func scrollableTitleBar(_ titleBar: ScrollableTitleBar, didSelected index: Int, title: String) {
        if index < pageChildViewControllers.count {
            let offsetY = currenPageChildController.getViewContentOffsetY()
            
            currenPageChildController = pageChildViewControllers[index] as! BXPUserHomeBaseTableViewController
            
            
            headerView.removeFromSuperview()
            currenPageChildController.setupHeaderView(headerView)
//            currenPageChildController.setViewContentOffset(offsetY: offsetY)
            if offsetY > headerViewHeight {
                currenPageChildController.setViewContentOffset(offsetY: headerViewHeight)
            } else {
                currenPageChildController.setViewContentOffset(offsetY: offsetY)
            }
            
            pageViewController.setViewControllers([currenPageChildController], direction: UIPageViewController.NavigationDirection.reverse, animated: false, completion: nil)
        }
    }
    
    //MARK: - BXPUserHomeBaseTableViewControllerDelegate
    func userHomeTableViewDidEndScrollView() {
        isPageScrollable = true
        headerView.removeFromSuperview()
        currenPageChildController.setupHeaderView(headerView)
    }
    
    enum UserHomeTopViewOffsetState {
        case lessThanTransparentTrigger  //offsetY 小于导航栏开始变透明所需的临界值
        case largeThanTitleBarFloat      //offsetY 大于titleBar浮动起来所需的临界值
        case equalNavigationTransparent  //offsetY 在上面两个值中间(即在导航栏透明度渐变的范围值中)
    }
    private var offsetYStyle = UserHomeTopViewOffsetState.lessThanTransparentTrigger//增加此属性目的是记录顶部视图的一些状态,用于比较,从而统一状态少设置(多比较,少赋值和设置)
    func userHomeBaseTableViewController(controller: BXPUserHomeBaseTableViewController, didScroll offsetY: CGFloat) {
        if controller != currenPageChildController {
            return
        }

        if offsetY <= 0 {
            headerView.setViewScaleWithTableViewOffset(offsetY: offsetY)
            return
        }

        let linjiezhi = headerViewHeight - 50 - 128
        let floatlinjie = headerViewHeight - 50 - 64

        if offsetY > linjiezhi { //导航栏开始透明度变化临界值
            if offsetY > floatlinjie {  //titleBar浮起来临界值
//                if offsetYStyle == .largeThanTitleBarFloat {
//                    return
//                }
//                offsetYStyle = .largeThanTitleBarFloat
                
                titleBar.removeFromSuperview()
                titleBar.frame = CGRect(x: 0, y: 64, width: view.bounds.size.width, height: 50)
                view.addSubview(titleBar)
                isStatusBarStyleDefault = true
                setNeedsStatusBarAppearanceUpdate()
                navigationController?.navigationBar.alpha = 1.0
                
                return
            }
            titleBar.removeFromSuperview()
            titleBar.frame = CGRect(x: 0, y: headerViewHeight - 50, width: view.bounds.size.width, height: 50)
            headerView.addSubview(titleBar)

            
            isStatusBarStyleDefault = false
            setNeedsStatusBarAppearanceUpdate()
            let alpha = (offsetY - linjiezhi) / CGFloat(64)
            print("------xp-----alpha=", alpha)
            navigationController?.navigationBar.alpha = alpha
            leftButton.alpha = 1.0 - alpha
            return
        }

        titleBar.removeFromSuperview()
        titleBar.frame = CGRect(x: 0, y: headerViewHeight - 50, width: view.bounds.size.width, height: 50)
        headerView.addSubview(titleBar)
        isStatusBarStyleDefault = false
        setNeedsStatusBarAppearanceUpdate()
        navigationController?.navigationBar.alpha = 0.01
        leftButton.alpha = 1.0
    }
    
    //MARK: - UIPageViewControllerDataSource, UIPageViewControllerDelegate
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        let index = pageChildViewControllers.index(of: viewController)
        if index == nil {
            return nil
        }
        if index == 0 {
            return nil
//            return pageChildViewControllers.last
        }
        if index! > 0 && pageChildViewControllers.count > 0 && index! < pageChildViewControllers.count {
            return pageChildViewControllers[index! - 1]
        }
        return nil
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        var index = pageChildViewControllers.index(of: viewController)
        if index == nil {
            return nil
        }
        index = index! + 1
        if pageChildViewControllers.count > 0 {
            if index! == pageChildViewControllers.count {
                return nil
//                return pageChildViewControllers.first
            }
            if index! < pageChildViewControllers.count {
                return pageChildViewControllers[index!]
            }
        }
        return nil
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if !finished {
            print("---xp-----didFinishAnimating-")
        }
//        let index = pageChildViewControllers.index(of: (pageViewController.viewControllers?.first)!)
//        if index != nil && index! >= 0 && index! < pageChildViewControllers.count {
//            
//            let currentVC = pageChildViewControllers[index!] as? BXPUserHomeBaseTableViewController
//            
//            if currentVC != nil {
//                headerView.removeFromSuperview()
//                currentVC?.setupHeaderView(headerView)
//                currenPageChildController = currentVC
//                print("---xp------page-finished--currentvc=nil")
//            }
//            
//            titleBar.setCurrentSelectedTitleWithIndex(index!)
//
//            print("---xp------page-finished--ok")
//        } else {
//            print("---xp------page-finished--nil")
//        }
    }
    
    //MARK: - UIScrollViewDelegate
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if !isPageScrollable {
            print("---xp-----page-scroll-beging-dragging---not")
            return
        }
        
        let headerFrame = headerView.superview?.convert(headerView.frame, to: view)
        if headerFrame == nil {
            isPageScrollable = false

            print("---xp-----page-scroll-beging-dragging---not--frame=nil")
            return
        }
        headerView.removeFromSuperview()
        headerView.frame = headerFrame!
        view.addSubview(headerView)
        
        let offsetY = currenPageChildController.getViewContentOffsetY()
        
        if offsetY > headerViewHeight { //需要头部视图全部偏移
            
            for viewController in pageChildViewControllers {
                if viewController == currenPageChildController {
                    continue
                }
                
                let userHomeVC = viewController as! BXPUserHomeBaseTableViewController
                if userHomeVC.tableView.contentOffset.y < headerViewHeight {
                    userHomeVC.setViewContentOffset(offsetY: headerViewHeight)
                }
            }
        } else { // 头部视图按照当前控制器中tableView的偏移量偏移
            for viewController in pageChildViewControllers {
                if viewController == currenPageChildController {
                    continue
                }
                
                let userHomeVC = viewController as! BXPUserHomeBaseTableViewController
                userHomeVC.setViewContentOffset(offsetY: offsetY)
            }
        }

        view.bringSubviewToFront(leftButton)

        print("---xp-----page-scroll-beging-dragging---yes")
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !isPageScrollable {
            scrollView.contentOffset = CGPoint(x: SCREEN_WIDTH, y: 0)
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            scrollViewDidEndDecelerating(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        isPageScrollable = true
//        headerView.removeFromSuperview()
//        currenPageChildController.setupHeaderView(headerView)

        print("---xp-----page-scroll-endscroll---")

        let index = pageChildViewControllers.index(of: (pageViewController.viewControllers?.first)!)
        if index != nil && index! >= 0 && index! < pageChildViewControllers.count {

            let currentVC = pageChildViewControllers[index!] as? BXPUserHomeBaseTableViewController

            if currentVC != nil {
                headerView.removeFromSuperview()
                currentVC?.setupHeaderView(headerView)
                currenPageChildController = currentVC
                print("---xp------page-finished--currentvc=nil")

                userHomeBaseTableViewController(controller: currenPageChildController, didScroll: currenPageChildController.getViewContentOffsetY())
            }

            titleBar.setCurrentSelectedTitleWithIndex(index!)

            print("---xp------page-finished--ok")
        } else {
            print("---xp------page-finished--nil")
        }
    }
    
    
    
    
    //MARK: - UIGestureRecognizerDelegate
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        let point = gestureRecognizer.location(in: gestureRecognizer.view)
        print("------xp----gesture--%f", point.y)

        return true
    }
    
    
    //MARK: - BXPUserHomeHeaderViewDelegate
    func userHomeHeaderViewDidClickedTopBackButton(_ headerView: BXPUserHomeHeaderView) {
        navigationController?.popViewController(animated: true)
    }
    
    func userHomeHeaderViewTouchDownAction(_ headerView: BXPUserHomeHeaderView) {
        isPageScrollable = false

         print("---xp-----userHomeHeaderViewTouchDownAction--isPageScrollable = false--")
    }
    
    func userHomeHeaderViewTouchUpAction(_ headerView: BXPUserHomeHeaderView) {
        isPageScrollable = true
    }
    
}
